<template>
  <div class="ad">
    <div class="header">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <el-input
            v-model="formInline.name"
            placeholder="请输入广告标题"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="formInline.content"
            placeholder="请输入广告内容"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit" icon="el-icon-search"
            >查找</el-button
          >
          <el-button type="primary" @click="handleAdd" class="el-icon-edit"
            >添加</el-button
          >
          <el-button
            type="primary"
            @click="handleDaochu"
            class="el-icon-download"
            >导出</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="main">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :default-sort="{ prop: 'date', order: 'descending' }"
      >
        <el-table-column prop="id" label="广告ID" align="center" sortable>
        </el-table-column>
        <el-table-column prop="name" label="广告标题" align="center">
        </el-table-column>
        <el-table-column prop="content" label="广告内容" align="center">
        </el-table-column>
        <el-table-column prop="url" label="广告图片" align="center">
          <template slot-scope="scope">
            <img :src="scope.row.url" alt="" />
          </template>
        </el-table-column>
        <el-table-column prop="position" label="广告位置" align="center">
        </el-table-column>
        <el-table-column prop="link" label="活动链接" align="center">
        </el-table-column>
        <el-table-column prop="enabled" label="是否启用" align="center">
          <template slot-scope="scope">
            <p v-if="scope.row.enabled == true">
              <el-tag type="success">启用</el-tag>
            </p>
            <p v-else>
              <el-tag>不启用</el-tag>
            </p>
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="操作"
          align="center"
          width="200px"
        >
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)" type="primary"
              >编辑</el-button
            >

            <el-button size="mini" @click="handleDel(scope.row)" type="danger"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </div>
    <!-- 对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="50%"
      @close="cancel"
    >
      <div class="box">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="广告标题" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="广告内容" prop="content">
            <el-input v-model="ruleForm.content"></el-input>
          </el-form-item>
          <el-form-item label="广告图片" prop="url">
            <el-upload
              class="avatar-uploader"
              :action="action"
              :show-file-list="false"
              :on-success="handleAvatarSuccessA"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="ruleForm.url" :src="ruleForm.url" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div class="el-upload__tip" slot="tip">
                只能上传jpg/png文件，且不超过1024kb
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="广告位置">
            <el-select v-model="ruleForm.position">
              <el-option label="首页" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="活动链接">
            <el-input v-model="ruleForm.link"></el-input>
          </el-form-item>
          <el-form-item label="是否启用">
            <el-select v-model="ruleForm.enabled">
              <el-option label="启用" value="1"></el-option>
              <el-option label="不启用" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm(1)" v-if="title == '创建'"
          >确 定</el-button
        >
        <el-button type="primary" @click="confirm(2)" v-if="title == '编辑'"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { listAd, createAd, updateAd,deleteAd } from "@/api/ad.js";
import pagination from "@/components/Pagination/index.vue";
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";
export default {
  // 标识,当前组件的名称
  name: "ad",
  data() {
    return {
      action: "http://admin.bsmall.byesame.com/admin/storage/create",
      title: "",
      dialogVisible: false,
      total: 0,
      formInline: {
        name: null,
        content: null,
      },
      tableData: [],
      ruleForm: {
        name: "",
        content: "",
        url: "",
        position: "1",
        link: "",
        enabled: "1",
      },
      obj: {},
      rules: {
        name: [
          { required: true, message: "广告标题不能为空", trigger: "blur" },
        ],
        content: [
          { required: true, message: "广告内容不能为空", trigger: "blur" },
        ],
        url: [{ required: true, message: "广告链接不能为空", trigger: "blur" }],
      },
      listQuery: {
        page: 1,
        limit: 20,
        sort: "add_time",
        order: "desc",
      },
      obj: {},
    };
  },
  methods: {
    getList() {
      listAd(this.listQuery)
        .then((response) => {
          this.tableData = response.data.data.list;
          this.total = response.data.data.total;
        })
        .catch(() => {
          this.tableData = [];
          this.total = 0;
        });
    },
    handleAvatarSuccessA(res, file) {
      console.log(res);
      this.ruleForm.url = URL.createObjectURL(file.raw);
      console.log(URL.createObjectURL(file.raw));
    },
    beforeAvatarUpload(file) {
      const isJPGOrPNG =
        file.type === "image/jpeg" || file.type === "image/png";
      const isLt1M = file.size / 1024 / 1024;

      if (!isJPGOrPNG) {
        this.$message.error("上传头像图片只能是 JPG 或 PNG 格式!");
      }
      if (!isLt1M) {
        this.$message.error("上传头像图片大小不能超过 1MB!");
      }
      return isJPGOrPNG && isLt1M;
    },
    // 导出
    handleDaochu() {
      // 创建一个workbook
      const workbook = XLSX.utils.book_new(); // 导出数据
      const worksheet = XLSX.utils.json_to_sheet(this.tableData);
      XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet 1"); // 将workbook转为二进制数据

      const excelData = XLSX.write(workbook, {
        type: "array",
        bookType: "xlsx",
      }); // 创建blob对象并保存excel文件
      const blob = new Blob([excelData], { type: "application/octet-stream" }); // 设置导出文件名字
      saveAs(blob, "data.xlsx");
    },
    // 查找
    onSubmit() {
      this.listQuery.name = this.formInline.name;
      this.listQuery.content = this.formInline.content;
      this.getList();
    },
    // 编辑
    handleEdit(row) {
      this.title = "编辑";
      this.dialogVisible = true;
      this.ruleForm.name = row.name;
      this.ruleForm.content = row.content;
      this.ruleForm.position = "1";
      this.ruleForm.url = row.url;
      this.ruleForm.link = row.link;
      if (row.enabled == true) {
        this.ruleForm.enabled = "1";
      } else {
        this.ruleForm.enabled = "0";
      }
      this.obj = JSON.parse(JSON.stringify(row));
    },
    // 删除
    handleDel(row) {
      deleteAd(row).then((response) => {
        this.$message({
          type: "success",
          message: "删除成功!",
        });
        this.getList();
      });
    },

    // 添加
    handleAdd() {
      this.title = "创建";
      // 打开模态框
      this.dialogVisible = true;
    },
    // 确定
    confirm(val) {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 添加对话框接口
          if (val === 1) {
            createAd(this.ruleForm).then((response) => {
              console.log(response);

              this.$message({
                type: "success",
                message: "新增成功!",
              });
              this.ruleForm = {
                name: "",
                content: "",
                url: "",
                position: "1",
                link: "",
                enabled: "1",
              };
              this.dialogVisible = false;
              this.getList();
            });
          }
          // 编辑对话框接口
          else {
            this.obj.name = this.ruleForm.name;
            this.obj.content = this.ruleForm.content;
            this.obj.url = this.ruleForm.url;
            this.obj.link = this.ruleForm.link;
            this.obj.enabled = this.ruleForm.enabled === "1" ? true : false;
            updateAd(this.obj).then((response) => {
              this.$message({
                type: "success",
                message: "更新成功!",
              });
              this.ruleForm = {
                name: "",
                content: "",
                url: "",
                position: "1",
                link: "",
                enabled: "1",
              };
              this.dialogVisible = false;
              this.getList();
            });
          }
        } else {
          return false;
        }
      });
    },
    // 取消
    cancel() {
      this.ruleForm = {
        name: "",
        content: "",
        url: "",
        position: "1",
        link: "",
        enabled: "1",
      };
      this.dialogVisible = false;
    },
  },
  components: {
    pagination,
  },
  mounted() {
    this.getList();
  },
};
</script>
<style lang="scss" scoped>
@import "./scss/ad.scss";
</style>